import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProDescriptions, ProFormCheckbox,
    ProFormText,
    ProFormTextArea,
    ProTable,
    ProFormDateRangePicker, ProFormDigit, ProFormUploadButton, ProFormSelect, ProFormDateTimePicker,
} from '@ant-design/pro-components';
import {Button, Drawer, Input, message, Modal, Tag, Badge, Space, Statistic, DatePicker} from 'antd';
import React, {useRef, useState} from 'react';
import type {LicenseListItem} from './data';
import {licenseList, licenseAdd, licenseDelete} from './service';

const {confirm} = Modal;
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: LicenseListItem) => {
    const hide = message.loading('正在添加');

    try {
        await licenseAdd({...fields});
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};
/**
 * 更新节点
 *
 * @param fields
 */

export type FormValueType = {
    target?: string;
    template?: string;
    type?: string;
    time?: string;
    frequency?: string;
} & Partial<LicenseListItem>;


/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: LicenseListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
        await licenseDelete({
            licenseIds: selectedRows.map((row) => row.licenseId),
        });
        hide();
        message.success('删除成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

const LicenseList: React.FC = () => {
    /** 新建窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    /** 分布更新窗口的弹窗 */
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [addContractModalVisible, handleAddContractVisible] = useState<boolean>(false);
    const [showDetail, setShowDetail] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<LicenseListItem>();
    const [selectedRowsState, setSelectedRows] = useState<LicenseListItem[]>([]);

    /** 国际化配置 */
    const columns: ProColumns<LicenseListItem>[] = [
        {
            title: 'licenseId',
            dataIndex: 'licenseId',
            search: false,
            hidden: true,
        },
        {
            title: '组织名称',
            dataIndex: 'organizationName',
            search: true,
        },
        {
            title: '系统版本',
            dataIndex: 'systemVersion',
            search: false,
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            search: false,
        },
        {
            title: '最大用户数',
            dataIndex: 'userLimit',
            search: false
        },
        {
            title: '最大资源数',
            dataIndex: 'resourceLimit',
            search: false,

        },
        {
            title: '有效期至',
            dataIndex: 'expireAt',
            search: false,
        },
        {
            title: '签发人',
            dataIndex: 'signer',
            search: false,
        },
        {
            title: 'license',
            dataIndex: 'license',
            search: false,
            hidden: true,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => {
                return [
                    <a
                        key="config"
                        onClick={() => {
                            handleUpdateModalVisible(true);
                            setCurrentRow(record);
                        }}
                    >
                        导出
                    </a>,
                ]
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<LicenseListItem, API.ListPagination>
                headerTitle="LICENSE列表"
                actionRef={actionRef}
                rowKey="licenseId"
                search={{
                    labelWidth: 90,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        <PlusOutlined/> 新建
                    </Button>,
                ]}
                request={licenseList}
                columns={columns}
                rowSelection={{
                    onChange: (_, selectedRows) => {
                        setSelectedRows(selectedRows);
                    },
                }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a
                                style={{
                                    fontWeight: 600,
                                }}
                            >
                                {selectedRowsState.length}
                            </a>{' '}
                            项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            confirm({
                                title: '删除LICENSE',
                                // icon: <ExclamationCircleFilled />,
                                content: '删除LICENSE并不影响私有化环境使用，是否现在删除?',
                                onOk() {
                                    handleRemove(selectedRowsState);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        批量删除
                    </Button>
                </FooterToolbar>
            )}

            <ModalForm
                title="添加LICENSE"
                width="550px"
                open={createModalVisible}
                onVisibleChange={handleModalVisible}
                onFinish={async (value) => {
                    const success = await handleAdd(value as LicenseListItem);
                    if (success) {
                        handleModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}

            >
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '组织名称为必填项',
                        },
                    ]}
                    // width="md"
                    name="organizationName"
                    label="组织名称"
                />
                <ProFormText
                    // width="md"
                    name="email"
                    label="邮箱"
                />
                <ProFormText
                    // width="md"
                    name="systemVersion"
                    label="系统版本"
                    initialValue={"v1.0"}
                />
                <ProFormDigit
                    // width="md"
                    name="userLimit"
                    label="最大用户数"
                    rules={[
                        {
                            required: true,
                            message: '最大用户数为必填项',
                        },
                    ]}
                    width={"md"}
                />
                <ProFormDigit
                    // width="md"
                    name="resourceLimit"
                    label="最大资源数"
                    width={"md"}
                    rules={[
                        {
                            required: true,
                            message: '最大资源数为必填项',
                        },
                    ]}
                />
                <ProFormDateTimePicker
                    label="有效期至"
                    width="md"
                    name="expireAt"
                    placeholder={'选择日期'}
                    rules={[
                        {
                            required: true,
                            message: '有效期至为必填项',
                        },
                    ]}
                    // disabled={true}
                />
            </ModalForm>

            <ModalForm
                title="LICENSE导出"
                width="550px"
                open={updateModalVisible}
                onVisibleChange={handleUpdateModalVisible}
                onFinish={async (value) => {
                    handleModalVisible(false);
                }}
                disabled={true}

                modalProps={
                    {
                        destroyOnClose: true,
                        okText: "关闭",
                        footer: null,
                    }
                }
                initialValues={{
                    license: currentRow?.license,
                }}
            >
                <ProFormTextArea
                    // width="md"
                    name="license"
                    label=""
                    fieldProps={{
                        rows: 15, // 设置文本域高度为 4 行
                    }}
                />

            </ModalForm>

            <Drawer
                width={600}
                open={showDetail}
                onClose={() => {
                    setCurrentRow(undefined);
                    setShowDetail(false);
                }}
                closable={false}
            >
                {currentRow?.licenseId && (
                    <ProDescriptions<LicenseListItem>
                        column={2}
                        title={currentRow?.licenseId}
                        request={async () => ({
                            data: currentRow || {},
                        })}
                        params={{
                            id: currentRow?.licenseId,
                        }}
                        columns={columns as ProDescriptionsItemProps<LicenseListItem>[]}
                    />
                )}
            </Drawer>
        </PageContainer>
    );
};

export default LicenseList;
